package com.cqyc.shop.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.commException;
import com.cqyc.shop.domain.User;
import com.cqyc.shop.services.UserServices;

@WebServlet(urlPatterns="/register.do")
public class RegisterServlet  extends HttpServlet{
	private static final long serialVersionUID = 8477764083390298528L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private UserServices userServices = new UserServices();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("执行注册方法");
		try {
			//1:从前台获取参数
				String usercode = request.getParameter("usercode");
				String username=request.getParameter("username");
				String password = request.getParameter("password");
				String brithday 	  =request.getParameter("brithday");
				String email  =request.getParameter("email");
				String phone = request.getParameter("phone");
				String sex = request.getParameter("sex");
				
				User user = new User();
				user.setUsercode(usercode);
				user.setUsername(username);
				user.setPassword(password);
				user.setEamil(email);
				user.setPhone(phone);
				user.setUsertype(0);
			//2:数据转换	
				if(brithday!=null) {
					user.setBrithday(df.parse(brithday));
				}
				if(sex!=null) {
					user.setSex(Integer.valueOf(sex));
				}
			//3:数据校验
				logger.debug("{}---{}--{}--{}--{}--{}--{}",user.getBrithday(),user.getPhone(),user.getUsercode(),user.getUsername(),user.getSex(),user.getEamil(),user.getPassword());
				if(usercode==null||usercode.length()<3 || username == null || username.length()<1|| password==null || password.length()<4 ||email ==null || phone==null) {
					throw new commException("所有字段不能为空哟，亲");
				}
				logger.debug("校验成功");
			//4:业务处理
				userServices.register(user);
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
			//5:跳转
				response.sendRedirect(request.getContextPath()+"/index.do");
				logger.debug("注册成功");
		} catch (Exception e) {
				logger.error("{}",e.getMessage());
				request.setAttribute("error",e.getMessage());
				request.getRequestDispatcher("/register.jsp").forward(request, response);
		}
	}

}
